<script lang="tsx">
import { defineComponent, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElButton, ElDrawer } from 'element-plus';
import { ChevronDown, ChevronRight, FolderCode, FileText } from '@vben/icons';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { getUserRegistrationInfoApi, type EduRegWorksVO } from '#/api/competition/registration-info';
import competitionNoDataImg from '#/assets/images/competition/competition_no_data.png';
import dayjs from 'dayjs';
import UploadWorksDialog from './components/upload-works-dialog.vue';
import VideoViewer from '#/views/lesson/modules/video-viewer.vue';
import { obsDownload } from '#/utils/obs';

export default defineComponent({
  name: 'UploadWorks',
  components: {
    UploadWorksDialog
  },
  props: {},
  emits: ['edit-registration', 'resubmit-registration'],
  setup(_props, { emit }) {
    const route = useRoute();
    const registrationList = ref<EduRegWorksVO[]>([]);
    const loading = ref(false);

    // 折叠状态管理：记录每个报名项的展开状态
    const expandedStates = ref<Record<string, boolean>>({});

    // 详情抽屉状态
    const detailDrawerVisible = ref(false);
    const currentDetail = ref<EduRegWorksVO | null>(null);

    const openDetailDrawer = (record: EduRegWorksVO) => {
      currentDetail.value = record;
      detailDrawerVisible.value = true;
    };

    const closeDetailDrawer = () => {
      detailDrawerVisible.value = false;
    };

    const getFileName = (key?: string) => {
      if (!key) return '';
      const parts = key.split('/');
      return parts[parts.length - 1] || key;
    };

    const handleDownload = (key?: string) => {
      if (!key) return;
      try {
        obsDownload({ Key: key }, (err: any, result: any) => {
          if (err) return;
          const content = result?.InterfaceResult?.Content as ArrayBuffer | undefined;
          if (!content) return;
          const blob = new Blob([content]);
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = getFileName(key);
          a.click();
          URL.revokeObjectURL(url);
        });
      } catch (e) {
        // 已有axios拦截统一提示
      }
    };

    // 获取报名信息
    const fetchRegistrationInfo = async () => {
      try {
        loading.value = true;
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        const response = await getUserRegistrationInfoApi({
          compId: matchId
        });
        registrationList.value = response || [];
      } catch (error) {
        console.error('获取报名信息失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 格式化日期
    const formatDate = (dateStr: string) => {
      if (!dateStr) return '--';
      try {
        return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
      } catch {
        return dateStr;
      }
    };

    // 计算剩余时间
    const calculateRemainingTime = (endTime: string) => {
      if (!endTime) return '';

      try {
        const now = new Date().getTime();
        const end = new Date(endTime).getTime();
        const diff = end - now;

        if (diff <= 0) {
          return '已截止';
        }

        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

        if (days > 0) {
          return `剩余 ${days} 天 ${hours} 小时`;
        } else if (hours > 0) {
          return `剩余 ${hours} 小时 ${minutes} 分钟`;
        } else {
          return `剩余 ${minutes} 分钟`;
        }
      } catch {
        return '时间格式错误';
      }
    };

    // 获取状态显示文本
    const getStatusText = (status: number, type: 'registration' | 'works') => {
      if (type === 'registration') {
        // registrationStatus: 0-草稿 1-待审核 2-通过 3-驳回
        switch (status) {
          case 0: return '待报名';
          case 1: return '待审核';
          case 2: return '通过';
          case 3: return '重新报名';
          default: return '-';
        }
      } else {
        // worksStatus: 0-未上传 1-待审核 2-通过 3-驳回
        switch (status) {
          case 0: return '未上传';
          case 1: return '待审核';
          case 2: return '通过';
          case 3: return '驳回';
          default: return '-';
        }
      }
    };

    // 获取综合状态信息
    // 结合 registrationStatus 和 worksStatus 生成统一的状态显示
    // 状态优先级：报名状态 > 作品状态
    const getOverallStatus = (registrationStatus: number, worksStatus: number) => {
      const regStatus = registrationStatus || 0;
      const workStatus = worksStatus || 0;

      // 报名相关状态（优先级最高）
      if (regStatus === 0) {
        return { text: '待报名', dot: 'bg-[#AEAEAE]' };
      }
      if (regStatus === 1) {
        return { text: '待审核', dot: 'bg-[#FB9A0E]' };
      }
      if (regStatus === 3) {
        return { text: '重新报名', dot: 'bg-[#E5484D]' };
      }

      // 报名通过后的作品状态
      if (regStatus === 2) {
        switch (workStatus) {
          case 0:
            return { text: '待上传', dot: 'bg-[#AEAEAE]' };
          case 1:
            return { text: '作品待审批', dot: 'bg-[#FB9A0E]' };
          case 2:
            return { text: '通过', dot: 'bg-[#30A46C]' };
          case 3:
            return { text: '作品驳回', dot: 'bg-[#E5484D]' };
          default:
            return { text: '待上传', dot: 'bg-[#AEAEAE]' };
        }
      }

      return { text: '未知状态', dot: 'bg-[#AEAEAE]' };
    };



    // 切换折叠状态 - 只响应箭头点击
    const toggleExpanded = (registrationId: string, event: Event) => {
      event.stopPropagation(); // 阻止事件冒泡
      expandedStates.value[registrationId] = !expandedStates.value[registrationId];
    };

    // 检查是否展开
    const isExpanded = (registrationId: string) => {
      return expandedStates.value[registrationId] || false;
    };

    // 上传作品弹窗相关
    const uploadDialogVisible = ref(false);
    const currentRegistration = ref<EduRegWorksVO | null>(null);

    // 处理上传作品
    const handleUploadWorks = (registration: EduRegWorksVO) => {
      currentRegistration.value = registration;
      uploadDialogVisible.value = true;
    };

    // 处理上传成功
    const handleUploadSuccess = async (data: any) => {
      console.log('上传成功:', data);
      // 这里可以调用API保存作品信息
      // 然后刷新列表
      await fetchRegistrationInfo();
    };

    // 处理编辑报名
    const handleEditRegistration = (registration: EduRegWorksVO) => {
      console.log('编辑报名:', registration);
      emit('edit-registration', registration);
    };

    // 处理重新提交报名
    const handleResubmitRegistration = (registration: EduRegWorksVO) => {
      console.log('重新提交报名:', registration);
      emit('resubmit-registration', registration);
    };

    // 渲染作品卡片头部（按原型图设计）
    const renderWorksHeader = (registration: EduRegWorksVO) => (
      <div class="flex items-center justify-between p-4 bg-white">
        <div class="flex items-center gap-3">
          {/* 折叠图标 - 只有箭头可点击 */}
          <div
            class="cursor-pointer p-1 hover:bg-gray-100 rounded transition-colors"
            onClick={(event) => toggleExpanded(registration.id || '', event)}
          >
            {isExpanded(registration.id || '') ?
              <ChevronDown class="w-5 h-5 text-gray-400" /> :
              <ChevronRight class="w-5 h-5 text-gray-400" />
            }
          </div>
          <h3 class="text-base font-medium text-gray-900 m-0">
            {registration.teamName}
          </h3>
        </div>
        {/* 作品基本信息 - 状态（前置圆点+文本） */}
        <div class="flex items-center gap-2">
          {(() => {
            const overallStatus = getOverallStatus(registration.registrationStatus || 0, registration.worksStatus || 0);
            return (
              <span class="inline-flex items-center text-[14px] leading-[22px] text-[#191919]">
                <span class={['inline-block w-2 h-2 rounded-full mr-2', overallStatus.dot]}></span>
                {overallStatus.text}
              </span>
            );
          })()}
        </div>
      </div>
    );

    // 渲染展开后的上方信息区域（图二信息）
    const renderUpperInfo = (registration: EduRegWorksVO) => (
      <div class="px-4 pt-0 pb-3 flex items-center">
        <div class="w-[48px] h-[48px] flex items-center justify-center rounded-full bg-[#CCE1F6] text-[#0067D1] mr-[16px]">
          <VbenIcon icon={FolderCode} class="w-[20px] h-[20px]" />
        </div>
        <div class="flex-1">
          <p class="text-[#191919] text-[14px] leading-[22px] font-[500]">{registration.worksName}</p>
          <p class="flex items-center grid grid-cols-3">
            <span>
              <span class="text-[12px] leading-[20px] text-[#2E73D4] py-[1px] px-[8px] bg-[#2893EB33]">{registration.groupName}</span>
            </span>
            <span class="text-[12px] leading-[20px] text-[#191919]">{registration.trackName}</span>
            <span>
              <el-button type="primary" link size="small" onClick={() => openDetailDrawer(registration)}>
                <VbenIcon icon={FileText} class="w-[16px] h-[16px]" />参赛作品详情
              </el-button>
            </span>
          </p>
        </div>
      </div>
    );

    // 渲染展开后的下方流程信息区域（图三信息）
    const renderProcessInfo = (registration: EduRegWorksVO) => (
      <div class="border border-[#DCDFE6] rounded-lg p-[24px] m-[24px]">
        <div class="flex items-start">
          {/* 左侧标题 */}
          <div class="text-[14px] leading-[22px] text-[#191919] mr-[8px]">
            报名状态
          </div>

          {/* 右侧三列状态区域 */}
          <div class="flex-1 grid grid-cols-3">
            {/* 报名状态列 */}
            <div class="flex">
              <div class="flex flex-col gap-[8px]">
                <div class="flex items-center">
                  <span class={[
                    'inline-block w-2 h-2 mr-2 align-middle rounded-full',
                    registration.registrationStatus === 0 ? 'bg-[#E5484D]' :
                      registration.registrationStatus === 1 ? 'bg-[#FB9A0E]' :
                        registration.registrationStatus === 2 ? 'bg-[#30A46C]' :
                          'bg-[#E5484D]'
                  ]}></span>
                  <span class="text-[14px] leading-[22px]">{getStatusText(registration.registrationStatus || 0, 'registration')}</span>
                </div>
                <div class="flex flex-col gap-[8px]">
                  <div class="text-[12px] text-[#595959]">
                    {formatDate(registration.registrationReviewTime || '')}
                    <span class={[
                      'mx-[8px]',
                      registration.registrationStatus === 2 ? 'text-[#30A46C]' :
                        registration.registrationStatus === 3 ? 'text-[#E5484D]' :
                          ''
                    ]}>
                      {registration.registrationStatus === 2
                        ? '通过'
                        : registration.registrationStatus === 3
                          ? '驳回'
                          : ''}
                    </span>
                    {registration.registrationReviewOpinion || ''}
                  </div>
                  <div>
                    {/* 编辑草稿 */}
                    {registration.registrationStatus === 0 && (
                      <ElButton size="small" type="primary" class="text-[12px]" onClick={() => handleEditRegistration(registration)}>
                        编辑草稿
                      </ElButton>
                    )}
                    {/* 重新报名按钮 */}
                    {registration.registrationStatus === 3 && (
                      <ElButton size="small" type="primary" class="text-[12px]" onClick={() => handleResubmitRegistration(registration)}>
                        重新报名
                      </ElButton>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* 上传作品列 */}
            <div class="flex gap-[8px]">
              <div class="text-[14px] leading-[22px] font-medium text-[#666666]">上传作品</div>
              <div class="flex flex-col gap-[8px]">
                <div class="flex items-center">
                  <span class={[
                    'inline-block w-2 h-2 mr-2 align-middle rounded-full',
                    registration.worksStatus === 2 ? 'bg-[#30A46C]' :
                      registration.worksStatus === 3 ? 'bg-[#E5484D]' :
                        registration.worksStatus === 1 ? 'bg-[#FB9A0E]' :
                          'bg-[#AEAEAE]'
                  ]}></span>
                  <span class="text-[14px] leading-[22px]">{getStatusText(registration.worksStatus || 0, 'works')}</span>
                </div>

                {/* 上传/修改作品按钮或提交作品显示 */}
                {registration.registrationStatus === 2 && (
                  <>
                    {[0, 3].includes(registration.worksStatus || 0) && (
                      <ElButton size="small" type="primary" class="text-[12px]" onClick={() => handleUploadWorks(registration)}>
                        上传作品
                      </ElButton>
                    )}
                  </>
                )}

                <div class="text-[12px] text-[#999999]">
                  {(registration.worksStatus || 0) >= 1 ?
                    `提交时间: ${formatDate(registration.registrationReviewTime || '')}` :
                    `${calculateRemainingTime(registration.worksLastTime || '')}`
                  }
                </div>
              </div>
            </div>

            {/* 作品审核列 */}
            <div class="flex gap-[8px]">
              <div class="text-[14px] leading-[22px] font-medium text-[#666666]">作品审核</div>
              <div class="flex flex-col">
                <div class="flex items-center">
                  <span class={[
                    'inline-block w-2 h-2 mr-2 align-middle rounded-full',
                    registration.worksStatus === 2 ? 'bg-[#30A46C]' :
                      registration.worksStatus === 3 ? 'bg-[#E5484D]' :
                        registration.worksStatus === 1 ? 'bg-[#FB9A0E]' :
                          'bg-[#AEAEAE]'
                  ]}></span>
                  <span class="text-[14px] leading-[22px]">{(registration.worksStatus || 0) >= 1 ? getStatusText(registration.worksStatus || 0, 'works') : '待提交'}</span>
                </div>
                <div class="text-[12px] leading-[22px] text-[#999999]">
                  {registration.worksReviewTime ? formatDate(registration.worksReviewTime) :
                    registration.worksReviewOpinion || '--'}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );

    // 渲染作品详细信息区域（展开后分为上下两个区域）
    const renderWorksDetails = (registration: EduRegWorksVO) => (
      <div class="">
        {/* 上方信息区域 */}
        {renderUpperInfo(registration)}

        {/* 下方流程信息区域 */}
        {renderProcessInfo(registration)}
      </div>
    );

    // 渲染单个可折叠的报名项
    const renderRegistrationItem = (registration: EduRegWorksVO) => (
      <div key={registration.id || registration.teamName} class="bg-white rounded-lg shadow-sm overflow-hidden">
        {/* 报名项头部 */}
        {renderWorksHeader(registration)}

        {/* 报名项详细信息（可折叠） */}
        {isExpanded(registration.id || '') && renderWorksDetails(registration)}
      </div>
    );

    // 渲染报名列表
    const renderRegistrationList = () => (
      <div class="w-full">
        {/* 可折叠的报名项列表 */}
        <div class="space-y-4">
          {registrationList.value.map(registration => renderRegistrationItem(registration))}
        </div>
      </div>
    );

    // 渲染空状态
    const renderEmptyState = () => (
      <div class="absolute top-0 left-0 w-full h-full flex flex-col items-center justify-center text-center">
        <img src={competitionNoDataImg} alt="暂无数据" class="max-w-48 max-h-48 mb-4" />
        <p class="text-gray-600 text-sm m-0">
          暂无报名信息，请先完成报名流程
        </p>
      </div>
    );

    // 渲染加载状态
    const renderLoadingState = () => (
      <div class="absolute top-0 left-0 w-full h-full flex flex-col items-center justify-center text-center">
        <div class="flex flex-col items-center">
          <div class="animate-spin rounded-full h-8 w-8"></div>
          <p class="text-gray-600 text-sm m-0">正在加载报名信息...</p>
        </div>
      </div>
    );

    // 组件挂载时获取数据
    onMounted(() => {
      fetchRegistrationInfo();
    });

    const renderDetailDrawer = () => (
      <ElDrawer
        v-model={detailDrawerVisible.value}
        title="参赛作品详情"
        size="65%"
        direction="rtl"
        append-to-body
        onClose={closeDetailDrawer}
      >
        {currentDetail.value && (
          <div class="pr-2">
            {/* 基本信息 */}
            <div>
              <div class="text-[14px] text-[#333] mb-3">基本信息</div>
              <div class="leading-[32px]">
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">作品名称</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.worksName || '--'}</div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">赛事组别</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.groupName || '--'}</div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">赛道</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.trackName || '--'}</div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">所属单位</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.organizationName || '--'}</div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">团队名称</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.teamName || '--'}</div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">专利文件</div>
                  <div class="col-span-5 text-[14px] text-[#191919] flex">
                    {currentDetail.value.worksPatent ? (
                      <a class="text-[#0067D1] text-[14px] w-full overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer" onClick={() => handleDownload(currentDetail.value!.worksPatent)}>
                        {getFileName(currentDetail.value.worksPatent)}
                      </a>
                    ) : (
                      <span>--</span>
                    )}
                  </div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">著作权文件</div>
                  <div class="col-span-5 text-[14px] text-[#191919] flex">
                    {currentDetail.value.worksCopyright ? (
                      <a class="text-[#0067D1] text-[14px] w-full overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer" onClick={() => handleDownload(currentDetail.value!.worksCopyright)}>
                        {getFileName(currentDetail.value.worksCopyright)}
                      </a>
                    ) : (
                      <span>--</span>
                    )}
                  </div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">授权证明</div>
                  <div class="col-span-5 text-[14px] text-[#191919] flex">
                    {currentDetail.value.listedDocName ? (
                      <a class="text-[#0067D1] text-[14px] w-full overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer" onClick={() => handleDownload(currentDetail.value!.listedDocName)}>
                        {getFileName(currentDetail.value.listedDocName)}
                      </a>
                    ) : (
                      <span>--</span>
                    )}
                  </div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">了解渠道</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.accessChannel || '--'}</div>
                </div>
              </div>
            </div>

            {/* 银行信息 */}
            <div>
              <div class="text-[14px] text-[#333] mb-3">银行信息</div>
              <div class="leading-[32px]">
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">收款账号</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.receivablesAccount || '--'}</div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">账户名</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.accountName || '--'}</div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">开户行</div>
                  <div class="col-span-5 text-[14px] text-[#191919]">{currentDetail.value.bankDeposit || '--'}</div>
                </div>
              </div>
            </div>

            {/* 作品信息 */}
            <div>
              <div class="text-[14px] text-[#333] mb-3">作品信息</div>
              <div class="leading-[32px]">
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">作品简介</div>
                  <div class="col-span-11 text-[14px] text-[#191919] whitespace-pre-wrap">{currentDetail.value.worksIntro || '--'}</div>
                </div>
                <div class="grid grid-cols-12 items-start gap-2">
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">作品介绍视频</div>
                  <div class="col-span-5">
                    {currentDetail.value.videoAssetId ? (
                      <div class="w-full"><VideoViewer path={`vod://${currentDetail.value.videoAssetId}`} vodAssetId={currentDetail.value.videoAssetId} /></div>
                    ) : (
                      <div class="w-full h-[150px] border border-dashed border-[#ddd] rounded flex items-center justify-center text-[#999] text-[12px]">暂无视频</div>
                    )}
                  </div>
                  <div class="col-span-1 text-right text-[14px] text-[#595959]">作品讲解课件</div>
                  <div class="col-span-5 flex">
                    {currentDetail.value.worksIntroduceFile ? (
                      <a class="text-[#0067D1] text-[14px] w-full overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer" onClick={() => handleDownload(currentDetail.value!.worksIntroduceFile)}>
                        {getFileName(currentDetail.value.worksIntroduceFile)}
                      </a>
                    ) : (
                      <div class="w-full h-[150px] border border-dashed border-[#ddd] rounded flex items-center justify-center text-[#999] text-[12px]">暂无课件</div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </ElDrawer>
    );

    return () => (
      <div class="w-full min-h-[616px] bg-white rounded-[16px]">
        {loading.value ?
          renderLoadingState() :
          registrationList.value.length > 0 ?
            renderRegistrationList() :
            renderEmptyState()
        }

        {/* 上传作品弹窗 */}
        <UploadWorksDialog
          visible={uploadDialogVisible.value}
          onUpdate:visible={(value: boolean) => uploadDialogVisible.value = value}
          registrationData={currentRegistration.value || undefined}
          onSuccess={handleUploadSuccess}
        />

        {/* 参赛作品详情抽屉 */}
        {renderDetailDrawer()}
      </div>
    );
  }
});
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.space-y-2>*+* {
  margin-top: 0.5rem;
}

.space-y-4>*+* {
  margin-top: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }

  .gap-x-6 {
    gap: 0.75rem;
  }

  .flex.gap-4 {
    flex-direction: column;
    gap: 0.5rem;
  }

  .px-6 {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}

@media (max-width: 480px) {
  .p-4 {
    padding: 0.75rem;
  }

  .gap-3 {
    gap: 0.5rem;
  }

  .text-lg {
    font-size: 1rem;
  }
}
</style>
